package sy.action;
import java.util.Arrays;
import java.util.Date;

import oracle.sql.DATE;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.springframework.beans.factory.annotation.Autowired;
import com.opensymphony.xwork2.ModelDriven;
import sy.model.Json;
import sy.pageModel.DataGrid;
import sy.pageModel.User;
import sy.service.UserServiceI;

@Namespace("/")
@Action("userAction")
public class UserAction extends BaseAction implements ModelDriven<User>{
	private User user=new User();
//	private static Logger log=Logger.getLogger(UserAction.class);
	@Autowired
	private UserServiceI uI;
 
	public void reg(){
 		Json j = new Json();
		try {
			uI.save(user);
			j.setSuccess(true);
			j.setMsg("注册成功!");
  		} catch (Exception e) {
 			j.setMsg(e.getMessage());
 		}
 		super.writeJson(j);
	 }
	public void login(){
	   Json json= new Json();
	   User u=uI.login(user);
	   if(u!=null){
		 json.setSuccess(true);
		 json.setMsg("登录成功!");
	   }else{
		   json.setMsg("登录失败,用户名或密码错误!");
	   }  
	   super.writeJson(json);
	}
	public void dataGrid(){
		DataGrid dataGrid=uI.dataGrid(user);
		super.writeJson(dataGrid);
	}
	public void add(){
 		Json j = new Json();
		try {
			System.out.println(uI.save(user));
			user=uI.login(user);//获取新增的对象
 			j.setSuccess(true);
			j.setMsg("新增成功!");
			j.setObj(user);
  		} catch (Exception e) {
 			j.setMsg(e.getMessage());
 		}
 		super.writeJson(j);
	 }
	public void remove(){
 		String ids=user.getIds();
		String[]nids=ids.split(",");
 		StringBuffer hql=new StringBuffer("delete from Tuser where id in(");
		for(int i=0;i<nids.length;i++){
			
			if(i>0){
				hql.append(",");
			}
			hql.append("'"+nids[i]+"'");
		}
		hql.append(")");
		int i=uI.remove(hql.toString());
		Json json=new Json();
		if(i<1){
			json.setMsg("删除失败!");
		}
		if(i>0){
			json.setSuccess(true);
			json.setMsg("成功删除"+i+"条!");
		}
		 
 		super.writeJson(json);
	}
	public void edit(){
      Json json=new Json();
     
	  try {
		  User u=uI.edit(user);
 		  json.setMsg("修改成功!");
		  json.setSuccess(true);
		  json.setObj(u);
	} catch (Exception e) {
		json.setMsg("修改失败,用户名已存在!");
		e.printStackTrace();
	}
	  super.writeJson(json);
		
	}
	@Override
	public User getModel() {
 		return user;
	}
		 
}
